import { useState, useEffect, useCallback } from 'react';

// 设备断点
export const BREAKPOINTS = {
  xs: 0,      // 超小屏幕
  sm: 640,    // 小屏幕 (手机)
  md: 768,    // 中等屏幕 (平板)
  lg: 1024,   // 大屏幕 (桌面)
  xl: 1280,   // 超大屏幕
  '2xl': 1536 // 2倍超大屏幕
} as const;

export type Breakpoint = keyof typeof BREAKPOINTS;

export const useMobileDetection = () => {
  const [isMobile, setIsMobile] = useState(false);
  const [screenSize, setScreenSize] = useState<{ width: number; height: number }>({ 
    width: window.innerWidth, 
    height: window.innerHeight 
  });
  const [breakpoint, setBreakpoint] = useState<Breakpoint>('lg');

  const checkDevice = useCallback(() => {
    const width = window.innerWidth;
    const height = window.innerHeight;
    
    // 更新屏幕尺寸
    setScreenSize({ width, height });
    
    // 检测是否为移动设备
    const isMobileDevice = width <= BREAKPOINTS.md;
    setIsMobile(isMobileDevice);
    
    // 确定当前断点
    let currentBreakpoint: Breakpoint = 'xs';
    for (const [key, value] of Object.entries(BREAKPOINTS)) {
      if (width >= value) {
        currentBreakpoint = key as Breakpoint;
      }
    }
    setBreakpoint(currentBreakpoint);
  }, []);

  useEffect(() => {
    // 初始检测
    checkDevice();
    
    // 监听窗口大小变化
    window.addEventListener('resize', checkDevice);
    
    // 监听设备方向变化
    window.addEventListener('orientationchange', checkDevice);
    
    return () => {
      window.removeEventListener('resize', checkDevice);
      window.removeEventListener('orientationchange', checkDevice);
    };
  }, [checkDevice]);

  // 检查是否达到特定断点
  const isBreakpoint = useCallback((breakpoint: Breakpoint) => {
    return screenSize.width >= BREAKPOINTS[breakpoint];
  }, [screenSize.width]);

  // 检查是否在特定断点范围内
  const isBetweenBreakpoints = useCallback((min: Breakpoint, max: Breakpoint) => {
    const width = screenSize.width;
    return width >= BREAKPOINTS[min] && width < BREAKPOINTS[max];
  }, [screenSize.width]);

  return {
    isMobile,
    screenSize,
    breakpoint,
    isBreakpoint,
    isBetweenBreakpoints,
    // 便捷方法
    isDesktop: breakpoint === 'lg' || breakpoint === 'xl' || breakpoint === '2xl',
    isTablet: breakpoint === 'md',
    isPhone: breakpoint === 'sm' || breakpoint === 'xs'
  };
};